import React, { Component } from 'react';
import { StyleSheet, Text, View, TextInput, FlatList, Image, Animated, TouchableOpacity, ScrollView, Modal, Alert, Platform, Dimensions } from "react-native";
import { GLOBAL } from '../../../config/global';
import { Common } from '../../../component/common/Common';
import { style } from '../../../theme/style';
import { API, API_GENERATE } from '../../../config/api';
import HTTP from '../../../utils/http';
import navigationSeevice from '../../../components/navigation/navigationSeevice';
import { CommonDialog } from '../../../components/common/Dialog';
import { PageStatusIndex } from '../../../component/page-status/PageStatusIndex';
import Upload from '../../../utils/Upload';
import ToastUtil from '../../../utils/toast';
import StorageHelper from '../../../utils/storageHelper';
import { STORAGE_CONSTANT } from '../../../config/storage';
import ModalPicsComponent from '../enterprise/details/_components/ModalPicsComponent';

var ImagePicker = require('react-native-image-picker');

const scale = GLOBAL.SCALE;
const selectIcon = require('../../../imgs/select.png');
const query = require('../../../imgs/global/query.png');
const defaultImg = require('../../../imgs/addphoto.png');
const correct = require('../../../imgs/global/correct.png');
const close = require('../../../imgs/global/error.png');
const closeImg = require('../../../imgs/close.png');

var imgOptions = {
  title: '请选择图片来源',
  cancelButtonTitle: '取消',
  takePhotoButtonTitle: '拍照',
  chooseFromLibraryButtonTitle: '相册图片',
  quality: 0.1,
  storageOptions: {
    skipBackup: true,
    path: 'images'
  }
};
var source = null;
const modalPicDelCfg = {
  visible: false,
  urls: [],
  picPress: () => { },
}
export class applicationDetailHis extends Component {
  static navigationOptions = ({ navigation, navigationOptions }) => {
    return {
      headerTitle: '用户认证信息',
      headerTintColor: style.color.white,
      headerLeft: <Common type="headLeft" onPress={() => { navigation.goBack() }} color='#fff' />,
      headerRight: (<Image style={style.head.headRightEmpty} source={require('../../../imgs/goBackEmpty.png')} />),
      headerStyle: {  // 头部整体样式 
        elevation: 0,
        borderBottomWidth: 0,
        backgroundColor: style.color.themeColor
      },
      headerTitleStyle: {
        flex: 1,
        textAlign: 'center'
      }
    }
  };

  constructor(props) {
    super(props);
    let { enterpriseMemberId } = props.navigation.state.params || {};
    this.state = {
      authorization: 'Y',
      imgServer: [],
      attachmentId: [],
      isLock: 'N',
      isFundsLock:'N',
      companyVisible: false,
      detailInfo: { enterpriseMemberLogVOs: [] },
      searchList: [],
      remarkVisible: false,
      operation: false,
      fileId: '',
      amplificationImage: false,
    };
    this.searchKey = '';
    this.oldId = '';
    this.params = {
      enterpriseMemberId: enterpriseMemberId,
    }
    this.imgUrl = []
    this.num =0
  }

  async componentWillMount () {
    this._initPage();
  }

  _initPage = async () => {
    let res = await HTTP.POST(API_GENERATE(API.HISTORY_INFO + '?enterpriseMemberId=' + this.params.enterpriseMemberId))
    this.setState({
      detailInfo: res,
      authorization: res.isAuth || 'N',
      isLock: res.isAuthFileMatch || 'N',
      isFundsLock:res.isAuthAccount || 'N',
      fileId: res.authorizationFile,
    })
    if (this.state.fileId) {
      this.getImgView()
    }
  }
  async getImgView () {
    qualificationArr = this.state.fileId.split(',');
    this.setState({ 
      attachmentId :qualificationArr
    })
    qualificationArr.map(async (fileId, index) => {
      await this.loadedImgs(fileId, qualificationArr.length);
    })
  }
  async	loadedImgs (fileId, length) {
    const response = await HTTP.GET(API_GENERATE(API.GET_IMG_VIEW), { fileId });
    if (response && response.image && response.image.length) {
      this.imgUrl.push(response.image);
    }
    this.num++
    if (length===this.num) {
      this.setState({ 
        imgServer: this.imgUrl ,
      })
      this.num = 0
    }
  }
  _amplification (index) {
    modalPicDelCfg.visible = true;
    modalPicDelCfg.urls.push({
      url: this.state.imgServer[index],
      width: Dimensions.get('window').width
    });
    modalPicDelCfg.picPress = () => {
      modalPicDelCfg.visible = false;
      modalPicDelCfg.urls = [];
      this.setState({
        amplificationImage: false
      })
    }
    this.setState({
      amplificationImage: true
    })
  }
  _authorization = (type) => {
    this.setState({ authorization: type })
  }
  _changeLog (index) {
    console.log(index)
    ImagePicker.showImagePicker(imgOptions, (response) => {
      if (response.didCancel) {
        console.log('用户取消了选择！');
      }
      else if (response.error) {
        console.log("ImagePicker发生错误：" + response.error);
      }
      else {
        source = { uri: response.uri };
        this._uploadImg(source, index);
      }
    });
  }
  async _uploadImg (imgUrl, index) {
    let uploadImgObj = {
      imgUrl,
      url: API_GENERATE(API.IMG_UPLOAD),
    }
    let responseData = await Upload.uploadImg(uploadImgObj);

    if (responseData) {
      let headObj = await HTTP.GET(API_GENERATE(API.GET_IMG_VIEW), { fileId: responseData.fileId }, null, 30000);
      if (headObj) {
        this.setState({
          headImg: { uri: headObj.image }
        })
      } else {
        this.setState({
          ls: true
        })
      }
      this._changeImg(responseData.fileId, this.state.imgUrl, index);
    }
  }
  async	_changeImg (fileId, imgUrl, index) {
    this.state.imgServer.splice(index, 0, source.uri);
    this.state.attachmentId.splice(index, 0, fileId);
    this.setState({
      imgServer: this.state.imgServer,
      attachmentId: this.state.attachmentId
    });
  }
  _delete (index) {
    this.state.imgServer.splice(index, 1);
    this.state.attachmentId.splice(index, 1);
    this.setState({
      imgServer: this.state.imgServer,
      attachmentId: this.state.attachmentId
    });
  }
  _checkFrozen () {
    if (this.state.isLock === 'Y') {
      this.setState({
        isLock: 'N',
        isFundsLock: 'N'
      })
    }
    else {
      this.setState({
        isLock: 'Y'
      })
    }

  }
  _checkFundsFrozen () {
    if (this.state.isFundsLock === 'Y') {
      this.setState({
        isFundsLock: 'N'
      })
    }
    else {
      this.setState({
        isFundsLock: 'Y'
      })
    }
  }
  //步骤栏
  _stepWrap () {
    const { enterpriseMemberLogVOs } = this.state.detailInfo;
    return (
      <View style={styles.stepWrap}>
        {enterpriseMemberLogVOs.map((item, index) => {
          return (
            <View style={{ flexDirection: 'row' }} key={index}>
              <Text style={[styles.recordText, { width: 40 * scale }]}>操作</Text>
              <View style={styles.recordType}>
                <View style={styles.recordCircle}>
                </View>
                {index === enterpriseMemberLogVOs.length - 1 ? null : <View style={styles.recordLine}></View>}
              </View>
              <View>
                <Text style={styles.recordText}>{item.createTime || '-'}</Text>
                <Text style={[styles.recordText, { width: 200 * scale }]}>{item.createName}</Text>
                <Text style={[styles.recordText, { width: 200 * scale }]}>备注：{item.comments || '-'}</Text>
              </View>
            </View>
          )
        })}
      </View>
    )
  }
  //关联企业
  _testInfo () {
    if (this.state.authorization === 'Y' && this.state.imgServer.length === 0) {
      Alert.alert('请添加授权委托证明')
      return
    }
    Alert.alert('提示',  '是否提交修改', [
      { text: '取消', onPress: () => { console.log('取消') } },
      { text: '好', onPress: () => { this._pushInfo() } },
    ]);
  }

  async _pushInfo () {
    const { authorization, isLock, attachmentId,isFundsLock } = this.state;
    this.params.isAuth = authorization
    this.params.isAuthFileMatch = isLock
    if(this.params.isAuth==='Y'){
      this.params.authorizationFile = attachmentId.toString()
    }
    else{
      this.params.authorizationFile = ''
    }
    if(isLock === 'Y'){
      this.params.isAuthAccount = isFundsLock
    }
    else{
      this.params.isAuthAccount = 'N'
    }
    console.log(this.params)
      let res = await HTTP.POST(API_GENERATE(API.ENTERPRICE_MEMBER_SUBMIT), this.params);
      if (res) {
        ToastUtil.showSuccess('提交修改成功').then(() => {
          this.props.navigation.navigate('claimRecord', { tabIndex: 3 });
        });
      }

  }
  render () {
    let { authorization, imgServer, isLock, detailInfo , remarkVisible, amplificationImage ,isFundsLock} = this.state;
    return (
      <View style={styles.container}>
        <View style={styles.radiu}></View>
        <ScrollView style={styles.bodyBox}>
          <View style={styles.createBox}>
            <View style={[styles.flexRow, styles.selectBox]}>
              <View style={styles.ItemHeadNewBox}></View>
              <TouchableOpacity
                style={[styles.flexRow, styles.select]}
              >
                <View style={styles.flexRow}>
                  <Text style={styles.selectTitle}>企业名称</Text>
                  <Text style={styles.selectContent}>{detailInfo.entName}</Text>
                </View>
              </TouchableOpacity>
            </View>
            <View style={[styles.flexRow, styles.selectBox]}>
              <View style={styles.ItemHeadNewBox}>
              </View>
              <View style={[styles.flexRow, styles.select]}>
                <View style={styles.flexRow}>
                  <Text style={styles.selectTitle}>用户姓名</Text>
                  <Text style={styles.nameContent}>{detailInfo.memUserName}</Text>
                </View>
              </View>
              <View style={styles.topBtnIconBox}>
              </View>
            </View>
            <View style={[styles.flexRow, styles.selectBox, { alignItems: 'stretch' }]}>
              <View style={styles.ItemHeadNewBox}>
              </View>
              <View
                style={[styles.flexRow, styles.select]}
              >
                <View style={styles.flexRow}>
                  <Text style={styles.selectTitle}>用户手机</Text>
                  <Text style={styles.mobileContent}>{detailInfo.memMobile}</Text>
                </View>
              </View>
              <View style={styles.topBtnIconBox}>
              </View>
            </View>
            <View style={[styles.flexRow, styles.selectBox]}>
              <View style={styles.ItemHeadNewBox}>
              </View>
              <View
                style={[styles.flexRow]}
              >
                <View style={{ flexDirection: 'row' }}>
                  <Text style={styles.selectTitle}>授权委托</Text>
                  <View>
                    <View style={styles.flexRow}>
                      <TouchableOpacity style={[styles.flexRow, { marginRight: 44 * scale }]} onPress={() => { this._authorization('Y') }}>
                        <View style={styles.selectCircle}>
                          {authorization === 'Y' ? <View style={styles.selectedCircle}></View> : null}
                        </View>
                        <Text style={styles.selectText}>有授权</Text>
                      </TouchableOpacity>
                      <TouchableOpacity style={styles.flexRow} onPress={() => { this._authorization('N') }}>
                        <View style={styles.selectCircle}>
                          {authorization === 'N' ? <View style={styles.selectedCircle}></View> : null}
                        </View>
                        <Text style={styles.selectText}>无授权</Text>
                      </TouchableOpacity>
                    </View>
                    {authorization === 'Y' ?
                      <View>
                        <View style={[styles.flexRow, { marginTop: 15 * scale }]}>
                          {
                            [1, 2, 3, 4].map((item, index) => {
                              return (
                                <View key={index} style={{ marginRight: 5, width: 35, height: 35, justifyContent: 'flex-end', position: 'relative' }}>
                                  {
                                    imgServer[index] ?
                                      <TouchableOpacity onPress={this._delete.bind(this, index)} style={{
                                        zIndex: 100, position: 'absolute', right: 0 * scale,
                                        top: 0 * scale, width: 12 * scale, height: 12 * scale
                                      }}>
                                        <Image style={styles.close} source={close} />
                                      </TouchableOpacity> : null
                                  }
                                  {imgServer[index] ?
                                    <TouchableOpacity onPress={() => { this._amplification(index) }}>
                                      <Image style={{ width: 30, height: 30 }}
                                        source={{ uri: imgServer[index] }}
                                      />
                                    </TouchableOpacity> :
                                    <TouchableOpacity onPress={this._changeLog.bind(this, index)}>
                                      <Image style={{ width: 30, height: 30 }}
                                        source={defaultImg} />
                                    </TouchableOpacity>
                                  }
                                </View>
                              )
                            })
                          }
                        </View>
                        <View style={[styles.flexRow, { marginTop: 10 * scale }]}>
                          <TouchableOpacity style={styles.enterpriseCircleBox} onPress={() => this._checkFrozen()}>
                            <View style={styles.lockView}>
                              {isLock === 'Y' ? <Image style={styles.lockImage} source={correct} /> : null}
                            </View>
                          </TouchableOpacity>
                          <Text style={{ color: '#000', fontSize: 12 }}>委托书与壹化网一致</Text>
                        </View>
                        {isLock === 'Y' ?
                          <View style={styles.flexRow}>
                            <TouchableOpacity style={styles.enterpriseCircleBox} onPress={() => this._checkFundsFrozen()}>
                              <View style={styles.lockView}>
                                {isFundsLock === 'Y' ? <Image style={styles.lockImage} source={correct} /> : null}
                              </View>
                            </TouchableOpacity>
                            <Text style={{ color: '#000', fontSize: 12 }}>是否可查资金账户</Text>
                          </View>:null
                        }
                      </View>
                      : null}
                  </View>
                </View>
              </View>
              <View style={styles.topBtnIconBox}>
              </View>
            </View>
            <View style={styles.bodyTextBox}>
              <Text style={styles.bodyTitle}>申请时间</Text>
              <Text style={styles.bodyText}>{detailInfo.createTime||'-'}</Text>
            </View>
            <View style={styles.bodyTextBox}>
              <Text style={styles.bodyTitle}>申请备注</Text>
              <Text style={[styles.bodyText, { width: 210 * scale }]}>{detailInfo.comments || '-'}</Text>
            </View>
            <View style={styles.bodyTextBox}>
              <Text style={styles.bodyTitle}>业务员</Text>
              <Text style={[styles.bodyText, { width: 210 * scale }]}>
                {detailInfo.bizStaffName || '-'}
                {detailInfo.bizStaffName && detailInfo.bizTeamName? 
                <Text style={styles.bodyText}>({detailInfo.bizTeamName})</Text> : null}</Text>
            </View>
            <View style={styles.bodyTextBox}>
              <Text style={styles.bodyTitle}>业务组织</Text>
              <Text style={[styles.bodyText, { width: 210 * scale }]}>{detailInfo.corpName || '-'}</Text>
            </View>
            {detailInfo.enterpriseMemberLogVOs.length > 0 ? this._stepWrap() : null}
          </View>
        </ScrollView>
        <View style={styles.bottomBox}>
            <TouchableOpacity style={[styles.button, { backgroundColor: '#0E5BC6' }]} onPress={() => { this._testInfo() }}>
              <Text style={{ color: '#fff', fontFamily: 'PingFangSC-Semibold' }}>提交修改</Text>
            </TouchableOpacity>
          </View>
          {amplificationImage ?<ModalPicsComponent {...modalPicDelCfg} /> : null}
        </View>
    )
  }
}


const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: style.color.themeColor
  },
  topBox: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between'
  },
  headBox: {
    paddingTop: 30 * scale,
    paddingBottom: 26 * scale,
    backgroundColor: style.color.themeColor
  },
  topTitle: {
    fontSize: 18 * scale,
    color: '#fff'
  },
  radiu: {
    marginTop: 13 * scale,
    height: 36 * scale,
    backgroundColor: '#fff',
    borderTopLeftRadius: 18 * scale,
    borderTopRightRadius: 18 * scale,
    marginBottom: -10 * scale
  },
  bodyBox: {
    flex: 1,
    backgroundColor: '#fff',
  },
  flexRow: {
    flexDirection: 'row',
    alignItems: 'center',
  },
  createBox: {
    paddingTop: 15 * scale,
    marginLeft: 30 * scale,
    marginRight: 30 * scale,
    marginBottom: 75 * scale
  },
  needed: {
    fontSize: 12 * scale,
    color: '#F80A0A',
    marginRight: 5 * scale,
  },
  selectBox: {
    marginBottom: 26 * scale,
    // alignItems: 'stretch',
  },
  select: {
    flex: 1,
    justifyContent: 'space-between',
    paddingBottom: 5 * scale,
  },
  selectTitle: {
    fontSize: 12 * scale,
    color: '#000000',
    marginRight: 30 * scale,
  },
  selectContent: {
    fontSize: 12 * scale,
    color: '#00A1FF',
    width: 180 * scale,
    fontWeight:'600'
  },
  selectedContent: {
    fontSize: 12 * scale,
    color: '#000',
    width: 180 * scale,
  },
  nameContent: {
    fontSize: 12 * scale,
    color: '#000000',
    fontFamily: 'PingFangSC-Semibold',
    width: 100 * scale,
    height: 20 * scale,
    paddingVertical: 0
  },
  mobileContent: {
    fontSize: 12 * scale,
    color: '#000000',
    // fontFamily: 'PingFangSC-Semibold',
    // opacity: 0.5
  },
  topBtnIconBox: {
    marginLeft: 10 * scale,
    width: 12 * scale,
  },
  topBtnIcon: {
    width: 12 * scale,
    height: 12 * scale,
  },
  ItemHeadNewBox: {
    width: 15 * scale,
    height: 15 * scale,
    marginRight: 10 * scale
  },
  ItemHeadNew: {
    width: 15 * scale,
    height: 15 * scale,
    backgroundColor: '#E02020',
    justifyContent: 'center',
    alignItems: 'center',
  },
  ItemHeadNewText: {
    color: '#fff',
    fontSize: 10 * scale,
    fontFamily: 'PingFangSC-Semibold'
  },
  selectCircle: {
    borderColor: '#0E5BC6',
    borderWidth: 1,
    borderRadius: 50,
    width: 12 * scale,
    height: 12 * scale,
    alignItems: 'center',
    justifyContent: 'center'
  },
  selectedCircle: {
    backgroundColor: '#98C1EB',
    width: 6 * scale,
    height: 6 * scale,
    borderRadius: 6 * scale
  },
  selectText: {
    marginLeft: 5 * scale,
    fontSize: 12 * scale
  },
  close: {
    width: 12 * scale,
    height: 12 * scale,
  },
  lockView: {
    flexDirection: 'row',
    justifyContent: 'center',
    alignItems: 'center',
    height: 13 * scale,
    width: 13 * scale,
    borderWidth: 1 * scale,
    borderColor: '#98C1EB',
    marginLeft: 5 * scale,
    marginRight: 10 * scale,
  },
  lockImage: {
    width: 8 * scale,
    height: 6 * scale
  },
  bodyTextBox: {
    marginLeft: 25 * scale,
    marginBottom: 25 * scale,
    flexDirection: 'row',
  },
  bodyTitle: {
    marginRight: 32 * scale,
    fontSize: 12,
    width: 50 * scale
  },
  bodyText: {
    fontSize: 12 * scale
  },
  bottomBox: {
    height: 100 * scale,
    backgroundColor: '#DFE3F0',
    zIndex: 100 * scale,
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'center',
    zIndex:1000
  },
  button: {
    borderRadius: 20 * scale,
    height: 38 * scale,
    alignItems: 'center',
    justifyContent: 'center',
    paddingLeft: 20 * scale,
    paddingRight: 20 * scale,
    borderWidth: 1,
    borderColor: '#0E5BC6'
  },
  stepWrap: {
    backgroundColor: '#F4F7FE',
    paddingTop: 20 * scale,
    // paddingBottom: 20,
    paddingLeft: 20 * scale,
  },
  textRowText: {
    fontSize: 11 * scale,
    lineHeight: 16 * scale,
    marginBottom: 10 * scale
  },
  textRow: {
    paddingLeft: 10 * scale,
    paddingRight: 10 * scale
  },
  recordType: {
    position: 'relative',
    height: 64 * scale,
    marginLeft: 13 * scale,
    marginTop: 4 * scale,
    marginRight: 15 * scale
  },
  recordCircle: {
    width: 6 * scale,
    height: 6 * scale,
    backgroundColor: '#959BA8',
    borderRadius: 6
  },
  recordLine: {
    height: 62 * scale,
    width: 0.5 * scale,
    backgroundColor: '#959BA8',
    position: 'absolute',
    top: 6 * scale,
    left: 2.5 * scale
  },
  recordText: {
    fontFamily: 'PingFangSC-Regular',
    fontSize: 10,
    color: '#959BA8',
    marginBottom: 2 * scale,
  },
  containerModal: {
    width: 375 * scale,
    height: GLOBAL.SCREEN_HEIGHT,
    justifyContent: 'flex-end',
  },
  bg: {
    width: 375 * scale,
    height: GLOBAL.SCREEN_HEIGHT,
    backgroundColor: 'rgba(0, 0, 0, .3)',
  },
  companyBox: {
    height: '75%',
    backgroundColor: 'rgba(0, 0, 0, .3)',
  },
  back: {
    backgroundColor: '#fff',
    height: '100%',
    borderTopLeftRadius: 15 * scale,
    borderTopRightRadius: 15 * scale,
    paddingBottom: 20 * scale

  },
  searchBox: {
    flexDirection: 'row',
    justifyContent: 'center',
    alignItems: 'center',
    marginTop: 15 * scale,
    marginBottom: 20 * scale
  },
  search: {
    flexDirection: 'row',
  },
  searchInput: {
    height: 37 * scale,
    width: 300 * scale,
    paddingLeft: 70 * scale,
    paddingRight: 12 * scale,
    backgroundColor: '#F4F7FE',
    flexDirection: 'row',
    justifyContent: 'center',
    alignItems: 'center',
    paddingVertical: 0,
    position: 'relative',
    borderRadius: 8 * scale,
    color: '#999898',
    fontSize: 12 * scale
  },
  searchIcon: {
    width: 18 * scale,
    height: 18 * scale,
    position: 'absolute',
    left: 24 * scale,
    top: 10 * scale,
    zIndex: 9,
    opacity: 0.8,
    tintColor: '#999898'
  },
  searchFilter: {
    fontSize: 25 * scale,
    color: '#fff',
    marginLeft: 17 * scale,
  },
  searchList: {
    height: 50 * scale,
    flexDirection: 'row',
    alignItems: 'center',
    paddingLeft: 38 * scale,
    paddingRight: 26 * scale,
    borderBottomWidth: 1,
    borderColor: '#E3E7F0',
    justifyContent: 'space-between'
  },
  enterpriseCircle: {
    width: 12 * scale,
    height: 12 * scale,
    borderRadius: 12 * scale,
    borderWidth: 1,
    borderColor: '#7D7E7F',
    opacity: 0.38
  },
  enterpriseImage: {
    width: 13 * scale,
    height: 13 * scale,
    marginLeft: 16 * scale
  },
  textInput: {
    borderWidth: 1 * scale,
    borderColor: '#000',
    borderRadius: 4 * scale,
    padding: 10 * scale,
    height: 122 * scale,
    fontSize: 12 * scale,
    marginTop: 10 * scale,
  },
  submitButton: {
    marginTop: 30 * scale,
    height: 35 * scale,
    width: 100 * scale,
    backgroundColor: '#0E7FFD',
    borderRadius: 15 * scale,
    alignSelf: 'center',
    justifyContent: 'center',
    alignItems: 'center',
  },
  modalPage: {
    width: GLOBAL.SCREEN_WIDTH,
    height: GLOBAL.SCREEN_HEIGHT,
    backgroundColor: 'rgba(0, 0, 0, .6)',
    justifyContent: 'center',
    alignItems: 'center',
  },
  modalWrap: {
    width: 302 * scale,
    backgroundColor: '#fff',
    borderRadius: 4 * scale,
    overflow: 'hidden',
    padding: 20 * scale,
    paddingTop: 10 * scale,
  },
  closeRemark: {
    width: 30 * scale,
    height: 30 * scale,
    flexDirection: 'row',
    justifyContent: 'flex-end',
    alignItems: 'center'
  },
  enterpriseCircleBox: {
    width: 30 * scale,
    height: 30 * scale,
    justifyContent: 'center',
    alignItems: 'center',
  }
})